import React from "react";
import Button from 'antd/lib/button';
import ConfigProvider from 'antd/lib/config-provider';
import Divider from 'antd/lib/divider';
import Modal from 'antd/lib/modal';
import Table from 'antd/lib/table';
import Tag from 'antd/lib/tag';
import zhCN from 'antd/es/locale/zh_CN';
import WorkFlowTable from "@/components/workflow/WorkFlowTable";
import notification from "@/services/notification";
import { get } from "lodash";
import { currentUser } from "@/services/auth";
import Workflow from "@/services/workflow";
import Workflow_transition from "@/services/workflow_transition";
import CreateTransitionDialog from "@/components/workflow/TransitionDialog";
import WarningOutlined from "@ant-design/icons/WarningOutlined";
import Customer from "@/services/customer";
import Tabletype from "@/services/tabletype";
import GlobalFunctions from '@/store/globalFunctions';
import {createBrowserHistory} from 'history';
const customHistory = createBrowserHistory();
const { confirm } = Modal;
export default class Toolbar extends React.Component {
  state = {
    loading: true,
    isnew: true,
    id: 0,
    userid: currentUser.id,
    name: "",
    orgunitid: 0,
    tabletypeid: 'contracts,0',
    is_active: false,
    transitiondata: [],
    page: 1,
    pagesize: 15,
    total: 15,
    employeedata:[],
    billtypedata:[],
    departmentdata:[],

  };
  componentWillMount() {
    if (this.props.id < 1 || this.props.id === undefined) {
      Workflow.getid({ id: 0 }).then(data => {
        this.setState({
          id: data[0].id,
          isnew: true,
          loading: false,
        });
      });
    } else {
      this.refreshData(this.props.id, false)
    }
    Customer.queryemployee({code: "",name: "",userid: currentUser.id,}).then(data => {
      this.setState({
        employeedata: data,
      });
    });
    let params={
      page: 1,
      pagesize: 100,
      code: '',
      name: '',
      userid: currentUser.id,
    }
    Tabletype.getlist(params).then(data => {

      this.setState({
        billtypedata: data.data,
      });
    });
     //HRP部门表
     params={
      code: "",
      name: "",
      userid: currentUser.id,
    }
    Customer.querydepartment(params).then(data => {
      this.setState({
        departmentdata: data,
      });
    });
  }
  refreshData(id = 0, isnew) {
    Workflow.get({ id: id }).then(data => {
      if (data.id > 0) {
        this.setState({
          isnew: isnew,
          id: data.id,//
          userid: data.userid,//--操作员ID
          name: data.name,
          orgunitid: data.orgunitid,
          tabletypeid: data.bill_enum+','+data.bill_type,
          is_active: data.is_active,
          loading: false,
        });
      } else {
        this.setState({
          loading: false,
          isnew: isnew,
          id: id,
          userid: currentUser.id,//--操作员ID
          name: "",
          orgunitid: 0,
          tabletypeid: 'contracts,0',
          is_active: false,
        });
      }
    }).catch(error => {
      this.setState({
        isnew: isnew,
        loading: false,
        id: id,
        userid: currentUser.id,//--操作员ID
        name: "",
        tabletypeid: 'contracts,0',
        orgunitid: 0,
        is_active: false,
      });
    });
    const params = {
      page: this.state.page,
      pagesize: this.state.pagesize,
      name: "",
      workflowid: id,
    }
    this.refresh_transitiondata(params, false);
  }
  refresh_transitiondata(params, flags) {
    let id;
    let userid;//--操作员ID
    let name;//--名称
    let orgunitid;
    let tabletypeid;
    let is_active;

    if (flags) {
      id = this.child.state.id;
      userid = this.child.state.userid;//--操作员ID
      name = this.child.state.name;//--名称
      orgunitid = this.child.state.orgunitid;
      tabletypeid= this.child.state.tabletypeid;
      is_active = this.child.state.is_active;
      Workflow_transition.getlist(params).then(data => {
        this.setState({
          loading: false,
          transitiondata: data.data,
          page: params.page,
          pagesize: params.pagesize,
          total: data.total,
          id: id,
          userid: userid,//--操作员ID
          name: name,//--名称
          orgunitid: orgunitid,
          tabletypeid: tabletypeid,
          is_active: is_active,
        });
      });
    } else {
      Workflow_transition.getlist(params).then(data => {
        this.setState({
          loading: false,
          transitiondata: data.data,
          page: params.page,
          pagesize: params.pagesize,
          total: data.total,
        });
      });
    }

  }
  handleadd = () => {
    Workflow.getid({ id: 0 }).then(data => {
      this.refreshData(data[0].id, true)
    });
  };
  ///|| str.match(/^[\s]*$/)
  isEmptyobj = (str) => {
    if (str === '' || str === null || str === 'null' || str === undefined || str === 'undefined') {
      return true;
    } else {
      return false;
    }
  }
  handleSave = () => {
    // if (currentUser.id !== this.child.state.userid) {
    //   notification.error("不是制单人，不能保存！");
    //   return;
    // }
    let name = this.child.state.name;
    if (GlobalFunctions.isEmptyobj(name)) {
      notification.error("名称不能为空");
      return;
    }
    let tabletypeid = this.child.state.tabletypeid;
    if (GlobalFunctions.isEmptyobj(tabletypeid)) {
      notification.error("单据不能为空");
      return;
    }
    let bill_enum= tabletypeid.split(',')[0];
    let bill_type = tabletypeid.split(',')[1];

    let data = {
      id: this.child.state.id,//
      userid: this.child.state.userid,//--操作员ID
      name: name,//--名称
      orgunitid: this.child.state.orgunitid,
      bill_enum: bill_enum,//--
      bill_type: bill_type,
      is_active: this.child.state.is_active
    }
    if (this.state.isnew) {
      Workflow.create(data)
        .then(() => {
          this.refreshData(this.state.id, false)
          notification.success("审批流程新增成功.");
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    } else {
      Workflow.save(data)
        .then(() => {
          notification.success("审批流程修改成功.");
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    }
  };
  handleDelete = () => {
    if (this.state.isnew) {
      notification.error("没有此审批流程！");
      return;
    }
    if (currentUser.id !== this.child.state.userid) {
      notification.error("不是制单人，不能删除！");
      return;
    }
    confirm({
      title: '确定删除审批流程?',
      icon: <WarningOutlined />,
      content: this.child.state.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Workflow.delete({ id: this.state.id }).then(() => {
          notification.success("审批流程删除成功.");
          Workflow.getid({ id: 0 }).then(data => {
            this.refreshData(data, true)
          });
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  handleDelete2 = (record) => {
    const params = {
      page: 1,
      pagesize: this.state.pagesize,
      name: "",
      workflowid: this.state.id,
    }
    confirm({
      title: '确定删除?',
      icon: <WarningOutlined />,
      // content: this.child.state.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Workflow_transition.delete({ id: record.id }).then(() => {
          notification.success("删除成功.");

          this.refresh_transitiondata(params, false);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  childchange = (data) => {
    this.setState({
      id: data.id,
      userid: data.userid,//--操作员ID
      name: data.name,//--名称
      orgunitid: data.orgunitid,
      tabletypeid: data.tabletypeid,
      is_active: data.is_active,
    });
  };
  handleUpdate = record => {
    let data = record;
    this.showCreateTransitionDialog(data);
  };
  showCreateTransitionDialog = (data) => {
    let params = data;
    if (data.id === 0) {
      params = {
        id: 0,
        workflow_stateid: 0,
        next_workflow_stateid: 0,
        allow_user: [],
        allow_group: [],
        condition: "",
        workflowid: this.state.id,
      }
    }
    CreateTransitionDialog.showModal({ transition: params })
      .onClose((result = {}) => {
        if (result.success) {
          let params = {
            page: this.state.page,
            pagesize: this.state.pagesize,
            name: "",
            workflowid: this.state.id,
          }
          this.refresh_transitiondata(params, true);
        }
      }).onDismiss(() => {
        //  navigateTo("orgstruct", true);
      });
  };
  handlebackpage= () => {
    customHistory.goBack();
  };
  handleTableChange = (pagination, filters, sorter) => {
    let params = {
      page: pagination.current,
      pagesize: pagination.pageSize,
      name: "",
      workflowid: this.state.id,
    }
    this.refresh_transitiondata(params, false);
  };
  render() {
    if (this.state.loading) return null;

    const paginationProps = {
      showSizeChanger: true,
      // showQuickJumper: true,
      total: this.state.total, // 数据总数
      pageSize: parseInt(this.state.pagesize), // 每页条数
      current: parseInt(this.state.page), // 当前页码
      pageSizeOptions: ["10", "20", "30", "100"],
      showTotal: ((total) => {
        return `共 ${total} 条`;
      }),
    };
    const columns = [
      {
        title: '状态',
        key: 'statename',
        dataIndex: 'statename',
        render: (text, record) => (
          <a className="clickable" onClick={() => this.handleUpdate(record)}>{text}</a>
        ),
      },
      {
        title: '行动',
        dataIndex: 'actionname',
        key: 'actionname',
      },
      {
        title: '下一状态',
        dataIndex: 'nextstatename',
        key: 'nextstatename',
      },
      {
        title: '用户审批',
        key: 'username',
        dataIndex: 'username',
        render: tags => (
          <span>
            {tags.map(tag => {
              return (
                <Tag>{tag}</Tag>
              );
            })}
          </span>
        ),
      },
      {
        title: '权限组审批',
        key: 'groupname',
        dataIndex: 'groupname',
        render: tags => (
          <span>
            {tags.map(tag => {
              return (
                <Tag>{tag}</Tag>
              );
            })}
          </span>
        ),
      },
      {
        title: '条件',
        dataIndex: 'condition',
        key: 'condition',
      },
      {
        title: '操作',
        key: 'action',
        render: (record) => (
          <span>
            <a className="clickable" onClick={() => this.handleDelete2(record)}>删除</a>
          </span>
        ),
      },
    ];
    const data = {
      id: this.state.id,
      userid: this.state.userid,//--操作员ID
      name: this.state.name,//--名称
      orgunitid: this.state.orgunitid,
      tabletypeid: this.state.tabletypeid,
      is_active: this.state.is_active,
      bill_type: this.state.bill_type,
    }
    return (
      <ConfigProvider locale={zhCN}>
        <div>
          <div style={{ marginBottom: 16 }}>
          <Button type="primary" style={{margin:"10px"}} onClick={() => this.handlebackpage()}>
            <i className="fa fa-reply m-r-5" />
            返回
          </Button>
          <Divider type="vertical" />
            <Button type="primary" onClick={() => this.handleadd()}>
              <i className="fa fa-plus m-r-5" />
              新增
            </Button>
            <Divider type="vertical" />
            <Button type="primary" onClick={() => this.handleSave()} >
              <i className="fa fa-save m-r-5" />
              保存
            </Button>
            <Divider type="vertical" />
            <Button type="primary" onClick={() => this.handleDelete()} >
              <i className="fa fa-trash m-r-5" />
              删除
            </Button>
          </div>
          <div>
            <WorkFlowTable data={data} 
            isedit={this.state.isedit} 
            employeedata={this.state.employeedata}
            billtypedata={this.state.billtypedata}
            departmentdata={this.state.departmentdata}
            onRef={(ref) => { this.child = ref; }} 
            childchange={this.childchange} />
          </div>
          <div>
            <div style={{ marginBottom: 16 }}>
              <span style={{ marginLeft: 8 }}>
                流程动作
              </span>
              <Divider type="vertical" />
              <Button type="primary" onClick={() => this.showCreateTransitionDialog({ id: 0 })}>
                <i className="fa fa-plus m-r-5" />
                新建
              </Button>
            </div>
            <Table rowKey='id'
              columns={columns}
              dataSource={this.state.transitiondata}
              pagination={paginationProps}
              onChange={this.handleTableChange}
            />
          </div>
        </div>
      </ConfigProvider>
    );
  };
}

